﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LBKDHelper.Models;
using LM.YF.K3Cloud.Plugin.Models.Grasses;
using LM.YF.K3Cloud.Plugin.Models.VOs;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin.BillPlugins
{
    [HotUpdate, Description("发货通知单表单插件")]
    public class 发货通知单 : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 销售组织
        /// </summary>
        private readonly ElementKeySchema FSaleOrgId = new ElementKeySchema
        {
            FormKey = "FSaleOrgId",
            DbKey = "FSALEORGID",
            OrmKey = "SaleOrgId"
        };

        /// <summary>
        /// 发货组织
        /// </summary>
        private readonly ElementKeySchema FDeliveryOrgID = new ElementKeySchema
        {
            FormKey = "FDeliveryOrgID",
            DbKey = "FDELIVERYORGID",
            OrmKey = "DeliveryOrgID"
        };

        /// <summary>
        /// 含税单价
        /// </summary>
        private readonly ElementKeySchema FTaxPrice = new ElementKeySchema
        {
            FormKey = "FTaxPrice",
            DbKey = "FTAXPRICE",
            OrmKey = "TaxPrice"
        };

        /// <summary>
        /// 结算单价
        /// </summary>
        private readonly ElementKeySchema F_RDLV_settlement_price = new ElementKeySchema
        {
            FormKey = "F_RDLV_settlement_price",
            DbKey = "F_RDLV_SETTLEMENT_PRICE",
            OrmKey = "F_RDLV_settlement_price"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        private readonly ElementKeySchema F_RDLV_saler2 = new ElementKeySchema
        {
            FormKey = "F_RDLV_saler2",
            DbKey = "F_RDLV_SALER2",
            OrmKey = "F_RDLV_saler2"
        };

        /// <summary>
        /// 单据编号
        /// </summary>
        private readonly ElementKeySchema FBillNo = new ElementKeySchema
        {
            FormKey = "FBillNo",
            DbKey = "FBILLNO",
            OrmKey = "BillNo"
        };

        /// <summary>
        /// 物料编码
        /// </summary>
        private readonly ElementKeySchema FMaterialID = new ElementKeySchema
        {
            FormKey = "FMaterialID",
            DbKey = "FMATERIALID",
            OrmKey = "MaterialID"
        };

        /// <summary>
        /// 结算币别
        /// </summary>
        private readonly ElementKeySchema FSettleCurrID = new ElementKeySchema
        {
            FormKey = "FSettleCurrID",
            DbKey = "FSETTLECURRID",
            OrmKey = "SettleCurrID"
        };

        /// <summary>
        /// 汇率
        /// </summary>
        private readonly ElementKeySchema FExchangeRate = new ElementKeySchema
        {
            FormKey = "FExchangeRate",
            DbKey = "FEXCHANGERATE",
            OrmKey = "ExchangeRate"
        };

        /// <summary>
        /// 结算系数
        /// </summary>
        private readonly ElementKeySchema F_RDLV_coefficient = new ElementKeySchema
        {
            FormKey = "F_RDLV_coefficient",
            DbKey = "F_RDLV_COEFFICIENT",
            OrmKey = "F_RDLV_coefficient"
        };

        /// <summary>
        /// 明细单据体
        /// </summary>
        private readonly ElementKeySchema FEntity = new ElementKeySchema
        {
            FormKey = "FEntity",
            DbKey = "T_SAL_DELIVERYNOTICEENTRY",
            OrmKey = "SAL_DELIVERYNOTICEENTRY"
        };

        /// <summary>
        /// 财务信息单据体
        /// </summary>
        private readonly ElementKeySchema SubHeadEntity = new ElementKeySchema
        {
            FormKey = "SubHeadEntity",
            DbKey = "T_SAL_DELIVERYNOTICEFIN",
            OrmKey = "SAL_DELIVERYNOTICEFIN"
        };

        /// <summary>
        /// 明细单据体-海空运费
        /// </summary>
        private readonly ElementKeySchema F_QLTK_SeaAirFreight = new ElementKeySchema
        {
            FormKey = "F_QLTK_SeaAirFreight",
            DbKey = "F_QLTK_SEAAIRFREIGHT",
            OrmKey = "F_QLTK_SeaAirFreight"
        };

        /// <summary>
        /// 明细单据体-保费
        /// </summary>
        private readonly ElementKeySchema F_QLTK_PREMIUM = new ElementKeySchema
        {
            FormKey = "F_QLTK_PREMIUM",
            DbKey = "F_QLTK_PREMIUM",
            OrmKey = "F_QLTK_PREMIUM"
        };

        /// <summary>
        /// 明细单据体-佣金
        /// </summary>
        private readonly ElementKeySchema F_QLTK_Commission = new ElementKeySchema
        {
            FormKey = "F_QLTK_Commission",
            DbKey = "F_QLTK_COMMISSION",
            OrmKey = "F_QLTK_Commission"
        };

        /// <summary>
        /// 明细单据体-其他1
        /// </summary>
        private readonly ElementKeySchema F_QLTK_Other1 = new ElementKeySchema
        {
            FormKey = "F_QLTK_Other1",
            DbKey = "F_QLTK_OTHER1",
            OrmKey = "F_QLTK_Other1"
        };

        /// <summary>
        /// 计价数量
        /// </summary>
        private readonly ElementKeySchema FPriceUnitQty = new ElementKeySchema
        {
            FormKey = "FPriceUnitQty",
            DbKey = "FPRICEUNITQTY",
            OrmKey = "PriceUnitQty"
        };

        /// <summary>
        /// 折扣额
        /// </summary>
        private readonly ElementKeySchema FDiscount = new ElementKeySchema
        {
            FormKey = "FDiscount",
            DbKey = "FDISCOUNT",
            OrmKey = "Discount"
        };

        /// <summary>
        /// 税率
        /// </summary>
        private readonly ElementKeySchema FEntryTaxRate = new ElementKeySchema
        {
            FormKey = "FEntryTaxRate",
            DbKey = "FTAXRATE",
            OrmKey = "TaxRate"
        };

        /// <summary>
        /// 本位币
        /// </summary>
        private readonly ElementKeySchema FLocalCurrID = new ElementKeySchema
        {
            FormKey = "FLocalCurrID",
            DbKey = "FLOCALCURRID",
            OrmKey = "LocalCurrID"
        };

        #endregion

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);

            var dataEntity = View.Model;
            var objSaleOrg = dataEntity.GetValue(FSaleOrgId.FormKey) as DynamicObject;
            var saleOrgName = (objSaleOrg?["Name"] as LocaleValue)?[2052];
            var objStockOrg = dataEntity.GetValue(FDeliveryOrgID.FormKey) as DynamicObject;
            var stockOrgName = (objStockOrg?["Name"] as LocaleValue)?[2052];

            if (!(/*new string[] { "利民控股集团股份有限公司", "河北威远生物化工有限公司" }.Contains(objSaleOrgName)
                &&*/ !stockOrgName.Equals(saleOrgName)))
            {
                return;
            }

            var stockOrgId = Convert.ToInt32(objStockOrg["Id"]);
            var saleOrgId = Convert.ToInt32(objSaleOrg["Id"]);
            var salerId = Convert.ToInt32((dataEntity.GetValue(F_RDLV_saler2.FormKey) as DynamicObject)?["Id"]);
            if (stockOrgId == 0 || saleOrgId == 0 || salerId == 0)
            {
                return;
            }

            var exchangeRate = 1M;// 汇率
            var settleCurr = Convert.ToInt32((dataEntity.GetValue(FSettleCurrID.FormKey, 0) as DynamicObject)?["Id"]);
            var isCny = settleCurr == 1;// 是否为人民币
            if (!isCny)
            {
                exchangeRate = Convert.ToDecimal(dataEntity.GetValue(FExchangeRate.FormKey, 0));
            }
            var entryCount = dataEntity.GetEntryRowCount(FEntity.FormKey);
            var localCurrId = Convert.ToInt32((dataEntity.GetValue(FLocalCurrID.FormKey, 0) as DynamicObject)?["Id"]);
            var vo = new avnn1
            {
                SaleOrgId = saleOrgId,
                ExchangeRate = exchangeRate,
                EntryDataCount = entryCount,
                SalerId = salerId,
                StockOrgId = stockOrgId,
                LocalCurrId = localCurrId
            };

            var vo2 = new vna1
            {
                GetInputs = entryIndex =>
                {
                    return new smznb111
                    {
                        Commission = Convert.ToDecimal(dataEntity.GetValue(F_QLTK_Commission.FormKey, entryIndex)),
                        OtherFee = Convert.ToDecimal(dataEntity.GetValue(F_QLTK_Other1.FormKey, entryIndex)),
                        Premium = Convert.ToDecimal(dataEntity.GetValue(F_QLTK_PREMIUM.FormKey, entryIndex)),
                        PriceQty = Convert.ToDecimal(dataEntity.GetValue(FPriceUnitQty.FormKey, entryIndex)),
                        SaFreight = Convert.ToDecimal(dataEntity.GetValue(F_QLTK_SeaAirFreight.FormKey, entryIndex)),
                        TaxPrice = Convert.ToDecimal(dataEntity.GetValue(FTaxPrice.FormKey, entryIndex)),
                        MaterialId = Convert.ToInt32((dataEntity.GetValue(FMaterialID.FormKey, entryIndex) as DynamicObject)?["Id"]),
                        TaxRate = Convert.ToDecimal(dataEntity.GetValue(FEntryTaxRate.FormKey, entryIndex)),
                        Discount = Convert.ToDecimal(dataEntity.GetValue(FDiscount.FormKey, entryIndex))
                    };
                },
                OnCalculated = (settlementPrice, coefficient, entryIndex) =>
                {
                    var entryId = Convert.ToInt32(dataEntity.GetEntryPKValue(FEntity.FormKey, entryIndex));
                    dataEntity.SetValue(F_RDLV_coefficient.FormKey, coefficient.ToString(), entryIndex);
                    dataEntity.SetValue(F_RDLV_settlement_price.FormKey, settlementPrice.ToString(), entryIndex);
                    DBUtils.Execute(Context, $@"update T_SAL_DELIVERYNOTICEENTRY
                        set F_RDLV_COEFFICIENT = {coefficient}, F_RDLV_SETTLEMENT_PRICE = {settlementPrice}
                        where FENTRYID = {entryId};");
                    // 更新发货通知单下游销售出库单的数据
                    DBUtils.Execute(Context, $@"update T_SAL_OUTSTOCKENTRY
                        set F_RDLV_COEFFICIENT = {coefficient}, F_RDLV_SETTLEMENT_PRICE = {settlementPrice}
                        where FENTRYID in (
                            select FENTRYID
                            from T_SAL_OUTSTOCKENTRY_LK
                            where FSTABLENAME = 'T_SAL_DELIVERYNOTICEENTRY'
                            and FSID = {entryId}
                        );");
                }
            };
            var failure = CalcSettlementPriceOperationServicePlugin.CalcSettlementPrice(Context, vo, vo2);

            if (!failure.Successful)
            {
                e.Cancel = true;
                var billNo = dataEntity.GetValue(FBillNo.FormKey)?.ToString();
                View.ShowErrMessage($"发货通知单【{billNo}】计算结算单价失败：{failure.Message}");
            }

            return;
        }
    }
}
